//创建用户相关的小仓库
import { defineStore } from "pinia";

import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
import type { UserState } from "./types/type";
import { getToken, removeToken, setToken } from "@/utils/token";
//引入路由（常量路由）
import { constantRoutes, anyRoutes, asyncRoutes } from "@/router/routes";
import type { loginFormData, loginResponseData, userInfoReponseData } from "@/api/user/type";
import type { RouteRecordRaw } from "vue-router";
import router from "@/router";
//引入深拷贝方法
//@ts-expect-error
import cloneDeep from "lodash/cloneDeep";

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoutes(asyncRoutes: RouteRecordRaw[], routes: string[]) {
  return asyncRoutes.filter((item) => {
    if(routes.includes(item.name as string)) {
      if(item.children && item.children.length > 0) {
        item.children = filterAsyncRoutes(item.children, routes);
      }
      return true;
    } else {
      return false;
    }
  })
}
//创建用户小仓库
let useUserStore = defineStore("user", {
  state: (): UserState => {
    return {
      token: getToken(),
      menuRoutes: constantRoutes,
      username: "",
      avatar: "",
      //存储当前用户需要展示的按钮
      buttons: [],
    };
  },
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data);
      //登录请求：成功200->token
      if (result.code === 200) {
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data as string;
        //所以需要本地持久化存储token
        setToken(result.data as string);
        return "ok";
      } else {
        //登录请求：失败201->message
        return Promise.reject(new Error(result.data));
      }
    },
    //获取用户信息的方法
    async userInfo() {
      //获取用户信息并存储
      let result:userInfoReponseData = await reqUserInfo();
      if (result.code === 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        this.buttons = result.data.buttons;
        let userAsyncRoutes = filterAsyncRoutes(cloneDeep(asyncRoutes), result.data.routes);
        this.menuRoutes = [...constantRoutes, ...userAsyncRoutes, ...anyRoutes];
        //目前路由器管理的只有常量路由。需要给路由器添加动态路由。
        [...userAsyncRoutes, ...anyRoutes].forEach((route) => {
          router.addRoute(route);
        })
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
    //退出登录的方法
    async userLogout() {
      //退出登录请求
      let result:any = await reqLogout();
      if (result.code === 200) {
        //清除token
        this.token = "";
        this.username = "";
        this.avatar = "";
        removeToken();
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
  },
  getters: {},
});
//对外暴露获取小仓库的方法
export default useUserStore;
